Channel is the Kotlin approach for handling a "hot stream" of items, where the work to build the items starts immediately, irrespective of whether anyone is around to consume the results.

A simple way to create a Channel is to use the produce() function on CoroutineScope. You provide a lambda expression, and it calls send() for every item that should be placed into the stream. Here, we send a series of random numbers, with a delay between each. Since produce() is defined on CoroutineScope, though, we need to either:

  • Call produce() from directly inside of our launch() coroutine builder (as this is a CoroutineScope in that lambda expression), or

  • Define our function that uses produce() (randomPercentages()) as an extension function on CoroutineScope

A simple way to consume a Channel is to call consumeEach(). This takes a lambda expression, and it is passed each send item from the Channel. consumeEach() is a suspend function, so we need to call consumeEach() from inside of another suspend function or from a coroutine builder, such as launch().

You can learn more about this in:
Tags:
Run Edit